package cn.chendd.example;

import junit.framework.TestCase;
import org.apache.commons.jci.compilers.CompilationResult;
import org.apache.commons.jci.compilers.JavaCompiler;
import org.apache.commons.jci.compilers.JavaCompilerFactory;
import org.apache.commons.jci.problems.CompilationProblem;
import org.apache.commons.jci.readers.FileResourceReader;
import org.apache.commons.jci.stores.FileResourceStore;

import java.io.File;
import java.util.Arrays;

/**
 * @author chendd
 * @date 2019/6/8 9:20
 * 包路径的java文件编译为class
 */
public class PackageClassCompiler extends TestCase {

    /**
     * @author chendd
     * @date 2019/6/8 9:22
     * 方法的描述：在sourceDir目录下将一些含包路径的java源文件编译为class
     */
    public void testSimpleTestCompiler() {

        String sources[] = new String[] { "cn/chendd/examples/SimpleTest.java" };
        File sourceDir = new File("D:\\test\\compiler");
        File targetDir = new File("D:\\test\\compiler");
        JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
        ClassLoader classloader = getClass().getClassLoader();
        CompilationResult result = compiler.compile(sources, new FileResourceReader(sourceDir),
                new FileResourceStore(targetDir) , classloader);
        CompilationProblem[] errors = result.getErrors();
        System.out.println(errors.length + " errors");
        if(errors.length > 1){
            System.out.println(Arrays.toString(errors));
        }
        System.out.println(result.getWarnings().length + " warnings");
    }

}
